<template>
	<view class="edit-advance-page">
		<!-- 自定義導航欄 -->
		<u-navbar
			title="编辑"
			:border="false"
			:auto-back="true"
			:bg-color="'#FFFFFF'"
			:title-color="'#333333'"
			:title-size="36"
			:title-weight="'bold'"
			placeholder
		>
			<template #right>
				<u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
				<u-icon name="eye" size="20" color="#333" @click="showViewOptions" style="margin-left: 20rpx;"></u-icon>
			</template>
		</u-navbar>

		<!-- 表单内容 -->
		<view class="form-content">
			<!-- 请假类型 -->
			<view class="form-item">
				<text class="form-label required">*请假类型</text>
				<view class="form-input" @click="showLeaveTypePicker">
					<text class="input-text">{{ formData.leaveType || '请选择' }}</text>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>

			<!-- 请假开始时间 -->
			<view class="form-item">
				<text class="form-label required">*请假开始时间</text>
				<view class="form-input" @click="showStartTimePicker">
					<text class="input-text">{{ formData.startTime || '请选择' }}</text>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>

			<!-- 请假结束时间 -->
			<view class="form-item">
				<text class="form-label required">*请假结束时间</text>
				<view class="form-input" @click="showEndTimePicker">
					<text class="input-text">{{ formData.endTime || '请选择' }}</text>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>

			<!-- 请假时长(天) -->
			<view class="form-item">
				<text class="form-label">请假时长(天)</text>
				<view class="form-input">
					<input 
						class="input-field" 
						v-model="formData.durationDays" 
						placeholder="请输入"
						type="number"
					/>
				</view>
			</view>

			<!-- 请假时长(小时) -->
			<view class="form-item">
				<text class="form-label">请假时长(小时)</text>
				<view class="form-input">
					<input 
						class="input-field" 
						v-model="formData.duration" 
						placeholder="0"
						type="number"
					/>
				</view>
			</view>

			<!-- 有薪请假时长(天) -->
			<view class="form-item">
				<text class="form-label">有薪请假时长(天)</text>
				<view class="form-input">
					<input 
						class="input-field" 
						v-model="formData.paidDuration" 
						placeholder="请输入"
						type="number"
					/>
				</view>
			</view>

			<!-- 有薪请假时长(小时) -->
			<view class="form-item">
				<text class="form-label">有薪请假时长(小时)</text>
				<view class="form-input">
					<input 
						class="input-field" 
						v-model="formData.paidDurationHours" 
						placeholder="0"
						type="number"
					/>
				</view>
			</view>

			<!-- 请假事由 -->
			<view class="form-item">
				<text class="form-label">请假事由</text>
				<view class="form-textarea">
					<textarea 
						class="textarea-field" 
						v-model="formData.reason" 
						placeholder="请输入"
						:maxlength="200"
					></textarea>
				</view>
			</view>
		</view>
		<!-- 底部操作按钮 -->
		<view class="bottom-actions">
			<button class="confirm-btn" @click="submitForm">
				<text class="btn-text">确定</text>
			</button>
		</view>

		<!-- 请假类型选择器 -->
		<u-popup :show="showLeaveTypeSelector" @close="closeLeaveTypeSelector" mode="bottom">
			<view class="picker-container">
				<view class="picker-header">
					<text class="picker-cancel" @click="closeLeaveTypeSelector">取消</text>
					<text class="picker-title">选择请假类型</text>
					<text class="picker-confirm" @click="confirmLeaveType">确认</text>
				</view>
				<picker-view 
					class="picker-view" 
					:value="leaveTypeIndex" 
					@change="onLeaveTypeChange"
				>
					<picker-view-column>
						<view class="picker-item" v-for="type in leaveTypes" :key="type">{{ type }}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</u-popup>

		<!-- 开始时间选择器 -->
		<u-datetime-picker
			:show="showStartTimeSelector"
			mode="datetime"
			v-model="startTimeValue"
			@confirm="confirmStartTime"
			@cancel="closeStartTimeSelector"
			:custom-style="{ 
				confirmColor: '#31a880',
				cancelColor: '#666666'
			}"
			:min-date="new Date('2020-01-01').getTime()"
			:max-date="new Date('2030-12-31').getTime()"
			:close-on-click-overlay="false"
			:show-toolbar="true"
			:title="'选择开始时间'"
			:z-index="1000"
		/>

		<!-- 结束时间选择器 -->
		<u-datetime-picker
			:show="showEndTimeSelector"
			mode="datetime"
			v-model="endTimeValue"
			@confirm="confirmEndTime"
			@cancel="closeEndTimeSelector"
			:custom-style="{ 
				confirmColor: '#31a880',
				cancelColor: '#666666'
			}"
			:min-date="new Date('2020-01-01').getTime()"
			:max-date="new Date('2030-12-31').getTime()"
			:close-on-click-overlay="false"
			:show-toolbar="true"
			:title="'选择结束时间'"
			:z-index="1000"
		/>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'

// API基础URL常量
const API_BASE_URL = 'https://hongjiang.hj-hr.com'

// 表单数据
const formData = reactive({
	id: '',
	leaveType: '',
	startTime: '',
	endTime: '',
	durationDays: 0,
	duration: 0,
	paidDuration: 0,
	paidDurationHours: 0,
	reason: ''
})

// 方法
const showMoreOptions = () => {
	uni.showActionSheet({
		itemList: ['保存草稿', '预览', '设置'],
		success: (res) => {
			console.log('选择了:', res.tapIndex)
		}
	})
}

const showSearch = () => {
	uni.showToast({
		title: '搜索功能',
		icon: 'none'
	})
}

const selectExpenseItem = (index: number) => {
	uni.navigateTo({
		url: `/pages/advance/filter?type=expense&index=${index}`
	})
}

const addLoanDetail = () => {
	formData.loanDetails.push({
		expenseItem: '',
		loanAmount: ''
	})
}

const copyDetail = (index: number) => {
	const detail = formData.loanDetails[index]
	formData.loanDetails.push({
		expenseItem: detail.expenseItem,
		loanAmount: detail.loanAmount
	})
	uni.showToast({
		title: '复制成功',
		icon: 'success'
	})
}

const deleteDetail = (index: number) => {
	if (formData.loanDetails.length <= 1) {
		uni.showToast({
			title: '至少保留一条借款明细',
			icon: 'none'
		})
		return
	}
	
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这条借款明细吗？',
		success: (res) => {
			if (res.confirm) {
				formData.loanDetails.splice(index, 1)
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
			}
		}
	})
}

const afterRead = (event: any) => {
	const { file } = event.detail
	formData.attachments.push(file)
	uni.showToast({
		title: `已选择${file.name}`,
		icon: 'success'
	})
}

// 判断是否为图片文件
const isImageFile = (fileName: string) => {
	if (!fileName) return false
	const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
	const lowerFileName = fileName.toLowerCase()
	return imageExtensions.some(ext => lowerFileName.endsWith(ext))
}

// 获取图片URL
const getImageUrl = (file: any) => {
	// 优先使用缩略图，如果没有则使用原图
	let imageUrl = file.thumbUrl || file.url || ''
	
	// 如果URL是相对路径，添加基础URL前缀
	if (imageUrl && !imageUrl.startsWith('http')) {
		imageUrl = API_BASE_URL + imageUrl
	}
	
	return imageUrl
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
	if (bytes === 0) return '0 B'
	const k = 1024
	const sizes = ['B', 'KB', 'MB', 'GB']
	const i = Math.floor(Math.log(bytes) / Math.log(k))
	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 预览图片
const previewImage = (file: any) => {
	if (!isImageFile(file.name)) {
		uni.showToast({
			title: '该文件不是图片，无法预览',
			icon: 'none'
		})
		return
	}
	
	const imageUrl = getImageUrl(file)
	if (!imageUrl) {
		uni.showToast({
			title: '图片地址无效',
			icon: 'none'
		})
		return
	}
	
	console.log('预览图片URL:', imageUrl)
	
	// 使用uni-app的图片预览功能
	uni.previewImage({
		current: imageUrl,
		urls: [imageUrl],
		success: () => {
			console.log('图片预览成功')
		},
		fail: (error) => {
			console.error('图片预览失败:', error)
			uni.showToast({
				title: '图片预览失败',
				icon: 'none'
			})
		}
	})
}

// 预览文件
const previewFile = (file: any) => {
	uni.showToast({
		title: '该文件类型不支持预览',
		icon: 'none'
	})
}

const deleteFile = (index: number) => {
	formData.attachments.splice(index, 1)
}

const validateForm = () => {
	if (!formData.reason.trim()) {
		uni.showToast({
			title: '请输入事由',
			icon: 'none'
		})
		return false
	}
	
	for (let i = 0; i < formData.loanDetails.length; i++) {
		const detail = formData.loanDetails[i]
		if (!detail.expenseItem) {
			uni.showToast({
				title: `请选择第${i + 1}条的费用项目`,
				icon: 'none'
			})
			return false
		}
		if (!detail.loanAmount) {
			uni.showToast({
				title: `请输入第${i + 1}条的借款金额`,
				icon: 'none'
			})
			return false
		}
	}
	
	return true
}

// 提交表单
const submitForm = async () => {
	// 验证必填字段
	if (!formData.leaveType) {
		uni.showToast({
			title: '请选择请假类型',
			icon: 'none'
		})
		return
	}
	
	if (!formData.startTime) {
		uni.showToast({
			title: '请选择开始时间',
			icon: 'none'
		})
		return
	}
	
	if (!formData.endTime) {
		uni.showToast({
			title: '请选择结束时间',
			icon: 'none'
		})
		return
	}
	
	try {
		// TODO: 调用实际的API接口
		// const response = await leaveApi.submitLeave(formData)
		
		uni.showToast({
			title: '请假申请提交成功',
			icon: 'success'
		})
		
		// 返回上一页
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
		
	} catch (error) {
		console.error('提交请假申请失败:', error)
		uni.showToast({
			title: '提交失败',
			icon: 'none'
		})
	}
}

const chooseFile = () => {
	uni.chooseFile({
		count: 9,
		type: 'file',
		success: (res) => {
			const file = res.tempFiles[0]
			formData.attachments.push(file)
			uni.showToast({
				title: `已选择${file.name}`,
				icon: 'success'
			})
		}
	})
}

// 请假类型选择器
const showLeaveTypeSelector = ref(false)
const leaveTypeIndex = ref(0)
const leaveTypes = ref(['事假', '病假', '调休假'])

// 时间选择器
const showStartTimeSelector = ref(false)
const showEndTimeSelector = ref(false)
const startTimeValue = ref(new Date().getTime())
const endTimeValue = ref(new Date().getTime())

// 显示请假类型选择器
const showLeaveTypePicker = () => {
	showLeaveTypeSelector.value = true
}

// 关闭请假类型选择器
const closeLeaveTypeSelector = () => {
	showLeaveTypeSelector.value = false
}

// 请假类型选择变化
const onLeaveTypeChange = (e: any) => {
	leaveTypeIndex.value = e.detail.value[0]
}

// 确认请假类型选择
const confirmLeaveType = () => {
	formData.leaveType = leaveTypes.value[leaveTypeIndex.value]
	closeLeaveTypeSelector()
}

// 显示开始时间选择器
const showStartTimePicker = () => {
	showStartTimeSelector.value = true
}

// 关闭开始时间选择器
const closeStartTimeSelector = () => {
	showStartTimeSelector.value = false
}

// 确认开始时间选择
const confirmStartTime = (value: number) => {
	formData.startTime = formatDateTime(value)
	closeStartTimeSelector()
}

// 显示结束时间选择器
const showEndTimePicker = () => {
	showEndTimeSelector.value = true
}

// 关闭结束时间选择器
const closeEndTimeSelector = () => {
	showEndTimeSelector.value = false
}

// 确认结束时间选择
const confirmEndTime = (value: number) => {
	formData.endTime = formatDateTime(value)
	closeEndTimeSelector()
}

// 格式化日期时间
const formatDateTime = (timestamp: number) => {
	const date = new Date(timestamp)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	return `${year}-${month}-${day} ${hours}:${minutes}`
}

onMounted(() => {
	console.log('编辑预支页面加载完成')
	// 这里可以根据传入的ID加载预支数据
})
</script>

<style lang="scss" scoped>
.edit-advance-page {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

/* 表单内容 */
.form-content {
	padding: 20rpx;
	padding-top: 120rpx; /* Adjust padding-top to account for navbar height */
}

.form-section {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	
	.section-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}
	
	.form-input, .amount-input {
		background-color: #F5F5F5;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
		color: #333;
		border: none;
	}
	
	.select-field {
		display: flex;
		align-items: center;
		background-color: #F5F5F5;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.select-text {
		flex: 1;
	}
	
	.select-arrow {
		font-size: 28rpx;
		color: #999;
		margin-left: 10rpx;
	}
	
	.form-field {
		margin-bottom: 20rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.field-label {
			display: block;
			font-size: 28rpx;
			color: #333333;
			margin-bottom: 15rpx;
			
			&.required::before {
				content: '*';
				color: #FF4757;
				margin-right: 5rpx;
			}
		}
	}
}

/* 借款明细 */
.loan-detail-item {
	background-color: #F8F8F8;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	
	.detail-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}
	
	.detail-number {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
	}
	
	.detail-actions {
		display: flex;
		gap: 10rpx;
	}
	
	.btn {
		padding: 8rpx 16rpx;
		font-size: 26rpx;
		border-radius: 8rpx;
	}
	
	.btn-primary {
		background-color: #FF6B35;
		border-color: #FF6B35;
		color: #FFFFFF;
	}
	
	.btn-error {
		background-color: #FF4757;
		border-color: #FF4757;
		color: #FFFFFF;
	}
}

/* 附件上传 */
.upload-area {
	padding: 20rpx;
	background-color: #F5F5F5;
	border-radius: 12rpx;
}

.file-item {
	display: flex;
	align-items: center;
	padding: 15rpx;
	background-color: #FFFFFF;
	border-radius: 8rpx;
	border: 1rpx solid #E0E0E0;
	margin-bottom: 15rpx;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: #F8F8F8;
		border-color: var(--u-primary);
	}
}

.file-thumbnail {
	width: 60rpx;
	height: 60rpx;
	border-radius: 6rpx;
	margin-right: 15rpx;
	flex-shrink: 0;
	cursor: pointer;
}

.file-icon {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #E0E0E0;
	border-radius: 6rpx;
	margin-right: 15rpx;
	flex-shrink: 0;
	cursor: pointer;
}

.icon-text {
	font-size: 32rpx;
	color: #666666;
}

.file-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 5rpx;
}

.file-name {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.file-size {
	font-size: 24rpx;
	color: #999999;
}

.file-name {
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.delete-file {
	font-size: 36rpx;
	color: #FF4757;
	margin-left: 10rpx;
}

.upload-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #FF6B35;
	border-radius: 8rpx;
	padding: 20rpx;
	color: #FFFFFF;
	font-size: 28rpx;
}

.upload-icon {
	font-size: 40rpx;
	margin-bottom: 10rpx;
}

.upload-text {
	font-size: 28rpx;
}

/* 提交按钮 */
.submit-button {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 30rpx;
	background-color: #FF6B35;
	color: #FFFFFF;
	font-size: 32rpx;
	border-radius: 8rpx;
	border: none;
	width: 100%;
}

/* 选择器样式 */
.picker-container {
	background-color: #FFFFFF;
	border-radius: 20rpx 20rpx 0 0;
	padding: 20rpx;
}

.picker-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #E5E5E5;
}

.picker-cancel {
	color: #666666;
	font-size: 28rpx;
}

.picker-title {
	color: #333333;
	font-size: 30rpx;
	font-weight: bold;
}

.picker-confirm {
	color: #31a880;
	font-size: 28rpx;
}

.picker-view {
	height: 400rpx;
}

.picker-item {
	line-height: 80rpx;
	text-align: center;
	font-size: 28rpx;
	color: #333333;
}

/* 底部操作按钮 */
.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	background-color: #FFFFFF;
	border-top: 1rpx solid #E5E5E5;
}

.confirm-btn {
	width: 100%;
	padding: 25rpx 0;
	background-color: #31a880;
	color: #FFFFFF;
	border: none;
	border-radius: 12rpx;
	font-size: 28rpx;
	font-weight: 500;
	cursor: pointer;
	transition: all 0.2s ease;
}

.confirm-btn:active {
	background-color: #27866a;
}

.btn-text {
	font-size: 28rpx;
	color: #FFFFFF;
}
</style>
